import socket
import threading


class ClientTalk(object):
    """
        提供客户端类
            1.构建客户端socket对象
            2.向服务端发起连接
            3.向服务端发消息
            4.从服务端接收消息
            5.关闭socket
    """

    def __init__(self):
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def connect_server(self, host, port):
        """
            建立和服务器的连接
        :return:
        """
        # 提供服务器地址
        address = (host, port)
        self.client.connect(address)

        # 收发消息
        threading.Thread(target=self.receive).start()
        threading.Thread(target=self.send).start()

    def send(self):
        """
        发消息
        :return:
        """
        while 1:
            to_msg = input(">>>")
            self.client.send(to_msg.encode("utf-8"))
            if to_msg == "bye":
                break

    def receive(self):
        while 1:
            from_msg = self.client.recv(1024).decode("utf-8")
            print("{}".format(from_msg))
        pass

    def __del__(self):
        self.client.close()


if __name__ == '__main__':
    tc = ClientTalk()
    tc.connect_server("127.0.0.1", 9669)
